//
//  UITableView+EmptyView.swift
//  MasterBoy
//
//  Created by kyson on 2023/4/21.
//

import Foundation

import UIKit

extension UITableView {
    func setEmptyView(title: String, message: String, icon: String = "ico_table_empty") {
        let emptyView = UIView(frame: CGRect(x: self.center.x,
                                             y: self.center.y,
                                             width: self.bounds.size.width,
                                             height: self.bounds.size.height))
        let emptyImageView = UIImageView()
        emptyImageView.translatesAutoresizingMaskIntoConstraints = false
        emptyImageView.image = UIImage(named: icon)
        
        let titleLabel = UILabel()
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        if #available(iOS 13.0, *) {
            titleLabel.textColor = .label
        } else {
            // Fallback on earlier versions
        }
        titleLabel.font = .systemFont(ofSize: 16, weight: .medium)
        titleLabel.text = title
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .center

        let messageLabel = UILabel()
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        if #available(iOS 13.0, *) {
            messageLabel.textColor = .secondaryLabel
        } else {
            // Fallback on earlier versions
        }
        messageLabel.font = .systemFont(ofSize: 14, weight: .thin)
        messageLabel.text = message
        messageLabel.numberOfLines = 0
        messageLabel.textAlignment = .center

        emptyView.addSubview(emptyImageView)
        emptyView.addSubview(titleLabel)
        emptyView.addSubview(messageLabel)
        NSLayoutConstraint.activate([
            emptyImageView.centerYAnchor.constraint(equalTo: emptyView.centerYAnchor, constant: -100),
            emptyImageView.centerXAnchor.constraint(equalTo: emptyView.centerXAnchor),
            emptyImageView.widthAnchor.constraint(equalToConstant: 100),
            emptyImageView.heightAnchor.constraint(equalToConstant: 100),
            titleLabel.centerYAnchor.constraint(equalTo: emptyView.centerYAnchor),
            titleLabel.centerXAnchor.constraint(equalTo: emptyView.centerXAnchor),
            titleLabel.leadingAnchor.constraint(equalTo: emptyView.leadingAnchor, constant: 20),
            titleLabel.trailingAnchor.constraint(equalTo: emptyView.trailingAnchor, constant: -20),
            messageLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
            messageLabel.leadingAnchor.constraint(equalTo: emptyView.leadingAnchor, constant: 20),
            messageLabel.trailingAnchor.constraint(equalTo: emptyView.trailingAnchor, constant: -20)
        ])
        self.backgroundView = emptyView
//        self.separatorStyle = .none
    }
    func restore() {
        self.backgroundView = nil
//        self.separatorStyle = .singleLine
    }
}
